<template>
	<view>
		<view class="content">
			<map id="map1" class="map" show-location="true" enable-building="true" ref="map1"></map>
		</view>
		<view class="btns">
			<button  @tap="carforward" >前进</button>
			<button  @tap="carback" >后退</button>
			<button  @tap="carleft" >左转</button>
			<button  @tap="carright" >右转</button>
			<button  @tap="carstop" >停止</button>
		</view>
		<view>
			<scroll-view :scroll-top="scrollTop" class="scroll"  id="msgList" scroll-y="true" scroll-with-animation="true">
				<block v-for="(item, index) in operationList" :key="index">
					<view style="float: left;">{{item}}</view>
				</block>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: '',
				operationList:[],
				scrollTop:120,
				mapContext:{},
				longitude:0,
				latitude:0
			}
		},
		onReady(){
			this.mapContext=uni.createMapContext("map1", this);
			if(!this.mapContext){
				this.mapContext=this.$refs.map1;
			}
			uni.getLocation({success:(res)=>{
				this.longitude= res.longitude;
				this.latitude= res.latitude;
				this.mapContext.moveToLocation({latitude:this.latitude,longitude:this.longitude,success:function(data){}});
			 }	
			});
			
		},
		onLoad() {
			//this.tcpsocket();
			//this.carforward();
			//this.carback();
			// this.carleft();
			// this.carright();
		},
		methods: {
			scrollCurr(){
				this.$nextTick(function() {
					this.scrollTop +=50;
				});
			},
			carforward(){ // 前进
				let data={"actionType":"0","action":"forward"};
				this.udpsocket(data);
			},
			carback(){ // 后退 
				let data={"actionType":"1","action":"back"};
				this.udpsocket(data);
			},
			carleft(){ // 左转 
				let data={"actionType":"2","action":"left"};
				this.udpsocket(data);
			},
			carright(){ // 右转 
				let data={"actionType":"3","action":"right"};
				this.udpsocket(data);
			},
			carstop(){ // 停止 
				let data={"actionType":"4","action":"stop"};
				this.udpsocket(data);
			},
			udpsocket(data){
				if (plus.os.name == "Android"){
					var DatagramPacket;  
					var DatagramSocket;  
					var InetAddress;   
					var JString;  
					var socket;  
					var port = 50001;  
					var timeout = 500;  
		
					try {   
						DatagramPacket = plus.android.importClass('java.net.DatagramPacket');  
						DatagramSocket = plus.android.importClass('java.net.DatagramSocket');  
						InetAddress = plus.android.importClass('java.net.InetAddress');  
						JString = plus.android.importClass('java.lang.String');  
		
						if (DatagramSocket == undefined) {     
							return;  
						}  
						socket = new DatagramSocket(port);  
						socket.setSoTimeout(timeout);  		
						// 创建广播地址  
						var broadcastAddress = InetAddress.getByName('192.168.8.134');  // 255.255.255.255
						// 发送广播数据  
					    this.operationList.push("发送："+JSON.stringify(data));
						var sendData = this.stringToBytes(JSON.stringify(data));  				
						var sendPacket = new DatagramPacket(sendData, sendData.length, broadcastAddress, port);  
						socket.send(sendPacket);  		
						// 接收数据  
						var isReceive = true;    
						while(isReceive){  
							try{  
								// 设置接收缓存，需要用0填充，否则为 null 无法接收。   
								var buffer = new Array(1024).fill(0);    
								var packet = new DatagramPacket(buffer, buffer.length);  
								socket.receive(packet);  
								var data = new JString(packet.getData()).trim(); 
								if (data.length == 0){  
									// 接收超时，结束接收  
									isReceive = false;  
								}else{   
								    this.operationList.push("接收："+data);
									this.scrollCurr();
								}   
							}catch(ex){   
								isReceive = false;  
							}  
						}         
					} catch (ex) {   
						console.log('===========出错了============',ex);  
					} finally {  
						if (socket != undefined){    
							socket.close();  
						}     
					}
				}
			},
			tcpsocket(data){
				if (plus.os.name == "Android") {
					var Socket = plus.android.importClass("java.net.Socket");
					var PrintWriter = plus.android.importClass("java.io.PrintWriter");
					var BufferedWriter = plus.android.importClass("java.io.BufferedWriter");
					var OutputStreamWriter = plus.android.importClass("java.io.OutputStreamWriter");
					var BufferedReader = plus.android.importClass("java.io.BufferedReader");
					var InputStreamReader = plus.android.importClass("java.io.InputStreamReader");
					
					var StrictMode = plus.android.importClass("android.os.StrictMode");
					var Build = plus.android.importClass("android.os.Build");
					if (Build.VERSION.SDK_INT > 9) {
						var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
						StrictMode.setThreadPolicy(policy);
					}
					console.log("连接服务器中... ");
					// uni.showModal({
					// 				   content: "连接服务器中...",
					// 				   showCancel: false
					// 			   });
					// this.socket = new Socket("192.168.8.134", 50001);
					// this.socket.setSoTimeout(5000);
					// console.log("连接服务器完成...");
					var socket = new Socket("192.168.8.134", 50001);
					socket.setSoTimeout(1500);
					var inputStreamReader = new InputStreamReader(socket.getInputStream());
					var socketReader = new BufferedReader(inputStreamReader);
					
					var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
					var bufferWriter = new BufferedWriter(outputStreamWriter);
					var socketWriter = new PrintWriter(bufferWriter, true);
					socketWriter.println(JSON.stringify(data));	
					this.operationList.push("发送："+JSON.stringify(data));
					var msgBeReceived = socketReader.readLine();
					console.log(msgBeReceived);		
					this.operationList.push("接收："+msgBeReceived);
					this.scrollCurr();
				}
			},stringToBytes:function (str) {  
				var bytes = new Array();  
				var len, c;  
				len = str.length;  
				for(var i = 0; i < len; i++) {  
					c = str.charCodeAt(i);  
					if(c >= 0x010000 && c <= 0x10FFFF) {  
						bytes.push(((c >> 18) & 0x07) | 0xF0);  
						bytes.push(((c >> 12) & 0x3F) | 0x80);  
						bytes.push(((c >> 6) & 0x3F) | 0x80);  
						bytes.push((c & 0x3F) | 0x80);  
					} else if(c >= 0x000800 && c <= 0x00FFFF) {  
						bytes.push(((c >> 12) & 0x0F) | 0xE0);  
						bytes.push(((c >> 6) & 0x3F) | 0x80);  
						bytes.push((c & 0x3F) | 0x80);  
					} else if(c >= 0x000080 && c <= 0x0007FF) {  
						bytes.push(((c >> 6) & 0x1F) | 0xC0);  
						bytes.push((c & 0x3F) | 0x80);  
					} else {  
						bytes.push(c & 0xFF);  
					}  
				}  
				return bytes;
			},
			byteToString(arr){
				if(typeof arr === 'string') {  
				   return arr;  
				}  
				var str = '', _arr = arr;  
				for(var i = 0; i < _arr.length; i++) {  
					var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/);  
					if(v && one.length == 8) {  
						var bytesLength = v[0].length;  
						var store = _arr[i].toString(2).slice(7 - bytesLength);  
						for(var st = 1; st < bytesLength; st++) {  
							store += _arr[st + i].toString(2).slice(2);  
						}  
						str += String.fromCharCode(parseInt(store, 2));  
						i += bytesLength - 1;  
					} else {  
						str += String.fromCharCode(_arr[i]);  
					}  
				}  
				return str;  
			},sendAction(data){
				var PrintWriter = plus.android.importClass("java.io.PrintWriter");
				var BufferedWriter = plus.android.importClass("java.io.BufferedWriter");
				var OutputStreamWriter = plus.android.importClass("java.io.OutputStreamWriter");
				var BufferedReader = plus.android.importClass("java.io.BufferedReader");
				var InputStreamReader = plus.android.importClass("java.io.InputStreamReader");
				
				let socket =this.socket;
				var inputStreamReader = new InputStreamReader(socket.getInputStream());
				var socketReader = new BufferedReader(inputStreamReader);
				
				var outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
				var bufferWriter = new BufferedWriter(outputStreamWriter);
				var socketWriter = new PrintWriter(bufferWriter, true);
				socketWriter.println(JSON.stringify(data));	
				this.operationList.push("发送："+JSON.stringify(data));
				var msgBeReceived = socketReader.readLine();
				console.log(msgBeReceived);		
				this.operationList.push("接收："+msgBeReceived);
			}
		}
	}
</script>

<style>
	.content {
		display: block;
		margin-left: 20rpx;
		/* flex-direction: column;
		align-items: center;
		justify-content: center; */
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	.map{
		height: 1200rpx; 
		width: 700rpx;
	}
	.scroll{
		margin-top: 10rpx;
		margin-left: 20rpx;
		height: 120rpx;
	}
	.btns{
		margin-top: 10rpx;
		display:block;
		flex-direction: column;
		justify-content: center;
		align-content: center;
	}
	.btns>button{
			position: relative;
			border: 0upx;
			display: inline-flex;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;
			padding: 0 30upx;
			font-size: 28upx;
			height: 100upx;
			width: 130upx;
			line-height: 1;
			text-align: center;
			text-decoration: none;
			overflow: visible;
			margin-left: 10rpx;
			transform: translate(0upx, 0upx);
			margin-right: initial;
	}
</style>
